import settings from "./settings";
import log from "./logger";
import axios from "axios";

// function send(metricName: string, value: string | boolean | number) {
//     let data = {
//         metric: metricName,
//         value: value,
//         tags: {name: settings.deviceName}
//     }
//     axios.post("http://localhost:4242/api/put", data).then((res) => {
//         console.log("post status:", data, res.status);
//     });
// }
function send(measurement: string, tags: object, field: string, value: string | boolean | number) {
    // weather,location=us-midwest temperature=82
    let data = measurement + ','

    for (let key in tags) {
        // @ts-ignore
        data += key + '=' + tags[key] + ','
    }
    data = data.substring(0, data.length - 1) + ' '
    data += field + '=' + value
    axios.post("http://vm.wechain360.com/write", data).then((res) => {
        log.info("post status:", data, res.status);
    }).catch(() => {
        log.error("metric post error")
    });
}

function getDateStr(date: Date) {
    const Y = date.getFullYear().toString().substring(2);
    const M = '' + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    const D = '' + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
    const h = '' + (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
    const m = '' + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
    const s = '' + (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    return Y + M + D + h + m + s;
}

function online(ms: number) {
    setInterval(() => {
        const date = new Date();
        const fullYear = getDateStr(date);
        send("vsNode", {deviceName: settings.code}, "online", Number(fullYear));
    }, ms);
}

function init(ms: number) {
    // 在线心跳
    online(ms);
}

export {init, send};